﻿using SqlSugar;
using System;
using System.IO;

namespace Core.DataAccess.Model
{
    /// <summary>
    /// 数据库实体生成器
    /// </summary>
    public class DataTabelBuilderOfModel
    {

        public string Connection { get; set; }
        public string BuilderFilePath { get; set; }
        public string NamespaceString { get; set; }

        public DataTabelBuilderOfModel(string connection, string builderFilePath, string namespaceString)
        {
            this.Connection = connection;
            this.BuilderFilePath = builderFilePath;
            this.NamespaceString = namespaceString;
        }

        public void Start()
        {

            //自动找最外层并 找到更外层 方便附加到其他项目中
            if (!string.IsNullOrEmpty(this.BuilderFilePath))
            {

                var basePath = new DirectoryInfo(Directory.GetCurrentDirectory());
                while ((basePath.FullName.Contains(@"\Debug") || basePath.FullName.Contains(@"\bin")) && !string.IsNullOrEmpty(basePath.FullName))
                {
                    basePath = basePath.Parent;
                }

                this.BuilderFilePath = Path.Combine(basePath.Parent.FullName, this.BuilderFilePath);
            }

            BuildModel(this.Connection, this.NamespaceString, this.BuilderFilePath);
        }

        private void BuildModel(string conn, string namespaceStr, string path)
        {
            try
            {
                Console.WriteLine("开始创建");

                var suger = this.GetInstance(conn).DbFirst.SettingClassTemplate(old =>
                {
                    return old.Replace("{Namespace}", namespaceStr);
                    //.Replace("class {ClassName}", "class {ClassName} :BaseEntity");//改变命名空间
                });

                suger.IsCreateDefaultValue();

                var tables = suger.ToClassStringList().Keys;
                suger.CreateClassFile(path);
                Console.WriteLine("创建完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public SqlSugarClient GetInstance(string conn)
        {
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conn,
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true
            });
            return db;
        }
    }
}
